package com.pine.dbant.common.plugin.meta.function.jdbc;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.plugin.meta.JdbcMetaAnalysisException;
import com.pine.dbant.common.plugin.meta.JdbcMetadataAnalysisConfig;
import com.pine.dbant.common.plugin.meta.QueryMetadataFunction;
import com.pine.dbant.common.plugin.meta.QueryMetadataParam;
import com.pine.sunflower.core.utils.Strings;

import java.util.Map;

/**
 * @author xiaoyuan
 * @create 2023/1/3 10:13
 **/
public class TableDDLFunction implements QueryMetadataFunction<JdbcMetadataAnalysisConfig, String> {
    @Override
    public String query(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String catalog = queryMetadataParam.getConfiguration().getNecessaryValue("catalog");
        String tableName = queryMetadataParam.getConfiguration().getNecessaryValue("tableName");
        String sql = "show create table `{}`.`{}`";
        Map<String, Object> record = JdbcUtils
                .getSqlRunner(metadataAnalysisConfig.getConnection())
                .selectOne(Strings.format(sql, catalog, tableName));
        if (record == null || record.size() != 2) {
            throw new JdbcMetaAnalysisException(Strings.format("获取表[{}]的DDL语句错误", tableName));
        }
        return String.valueOf(record.get("Create Table"));
    }

    @Override
    public String getType() {
        return "DDL";
    }
}
